import { Component } from 'react';
import * as React from 'react';
import { NaggetCard, NaggetCardProps } from './NaggetCard';

const axios = require('axios');

export interface NaggetTimelineProps {
	url: string;
}

export interface NaggetTimelineState {
	skip: Date;
	items: Array<NaggetCardProps>;
	loading: boolean;
	exhausted: boolean;
}

export class NaggetTimeline extends Component<NaggetTimelineProps, NaggetTimelineState> {
	constructor(props: NaggetTimelineProps) {
		super(props);
		this.state = {
			skip: new Date(),
			items: [],
			loading: false,
			exhausted: false
		};
	}

	public render() {
		let elements: Array<any> = [];
		this.state.items.forEach(it => {
			elements.push(<NaggetCard _id={it._id} content={it.content} username={it.username} postTime={it.postTime} />)
		});
		return (<div className={"nagget-timeline"}>
			{elements}
			<div className={"nagget-timeline-exhausted"} hidden={!this.state.exhausted} aria-hidden={!this.state.exhausted}>
				<span className={"nagget-timeline-exhausted-text"}>That's all, folks!</span>
			</div>
			<div className={"nagget-timeline-more"}>
				{this.state.loading ? <button className={"nagget-timeline-more-btn"} disabled={true} aria-disabled={true}>Load More</button> : <button className={"nagget-timeline-more-btn"} onClick={this.loadMore.bind(this)}>Load More</button>}
			</div>
		</div>);
	}

	private async loadMore() {
		this.setState({
			loading: true
		});
		try {
			let out = await axios.get(this.props.url, {
				params: {
					limit: 20,
					skip: this.state.skip.toISOString()
				}
			});
			if (out.status == 200) {
				let data: Array<NaggetCardProps>;
				if (typeof out.data == 'string') {
					data = JSON.parse(out.data);
				} else {
					// parsed already?
					data = out.data;
				}
				if (data.length < 20) {
					this.setState({
						exhausted: true
					});
				}
				if (data.length > 0) {
					let last = data[data.length - 1];
					this.setState({
						skip: new Date(last.postTime),
						items: this.state.items.concat(data)
					});
				}
			} else {
				// TODO: error occurred!
				console.log(out);
			}
		} finally {
			this.setState({
				loading: false
			});
		}
	}
}